package com.android.example;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.TextView;


public class CanvasDrawingActivity extends  Activity   {
	private ArrayList<Path> _graphics = new ArrayList<Path>();
	private Paint mPaint;
	private  String clientMessage;
	static ServerSocket providerSocket;
	Socket connection = null;
	static ObjectOutputStream out;
	ObjectInputStream in;
	String message;
	private static TextView serverStatus;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CanvasDrawingActivity obj = new CanvasDrawingActivity();
       //obj.createConnection();
        setContentView(new DrawingPanel(this));
        Log.d("Draw","In onCreate");
        mPaint = new Paint();
        mPaint.setDither(true);   
        mPaint.setColor(0xFFFFFFFF);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeWidth(3);
		
	}
	
	protected void onStop(){
		Log.d("Draw:","Bye Bye!!!");
		try{
			in.close();
			out.close();
		providerSocket.close();
		}catch(Exception ex){}
   		System.exit(0);
	}
	public static void sendMessage(String msg)
	{
		try{
			out.writeObject(msg);
			out.flush();
			Log.d("Draw", msg);
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}
	}
	 private void createConnection(){
	    	try{
	    	serverStatus = (TextView) findViewById(R.id.server_status);
	    	Log.d("Draw","In createConnection");
	    	providerSocket = new ServerSocket(4444);
	    	Log.d("Draw","Listening.."+InetAddress.getLocalHost().getHostAddress());
	    	serverStatus.setText("Listening.."+InetAddress.getLocalHost().getHostAddress());
			Socket client = providerSocket.accept();
			Log.d("Draw","Connected to client "+client.getLocalSocketAddress());
			serverStatus.append("Connected to client "+client.getLocalSocketAddress());
			ObjectInputStream in = new ObjectInputStream(client.getInputStream());
			String message = (String)in.readObject();
			out = new ObjectOutputStream(client.getOutputStream());
			out.flush();
			sendMessage("HI");
	    	}catch(Exception ex){
	    		Log.d("Draw","Error");
	    	}
	    }
	 
	class DrawingPanel extends SurfaceView implements SurfaceHolder.Callback {
		private DrawingThread _thread;
		private Path path;
				
		public DrawingPanel(Context context) {
			super(context);
            getHolder().addCallback(this);
            _thread = new DrawingThread(getHolder(), this);
            Log.d("Draw","In DrawingPanel Constructor");
		}
		
		
        public boolean onTouchEvent(MotionEvent event) {
        	Log.d("Draw","In onTouchEvent");
            synchronized (_thread.getSurfaceHolder()) {
            	if(event.getAction() == MotionEvent.ACTION_DOWN){
            		path = new Path();
            		path.moveTo(event.getX(), event.getY());
            		path.lineTo(event.getX(), event.getY());
            		_graphics.add(path);
            	}else if(event.getAction() == MotionEvent.ACTION_MOVE){
            		path.lineTo(event.getX(), event.getY());
            		
            	}else if(event.getAction() == MotionEvent.ACTION_UP){
            		path.lineTo(event.getX(), event.getY());
            		//_graphics.add(path);
            	}
            	
            	return true;
            }
		}
		
		@Override
        public void onDraw(Canvas canvas) {
			for (Path path : _graphics) {
				//canvas.drawPoint(graphic.x, graphic.y, mPaint);
				Log.d("Draw","In onDraw"+path);
				canvas.drawPath(path, mPaint);
			}
		}
		
		public void surfaceChanged(SurfaceHolder holder, int format, int width,
								   int height) {
			// TODO Auto-generated method stub
			
		
		}
		
		public void surfaceCreated(SurfaceHolder holder) {
			// TODO Auto-generated method stub
			Log.d("Draw","In surfaceCreated");
			_thread.setRunning(true);
            _thread.start();
		}
		
		public void surfaceDestroyed(SurfaceHolder holder) {
			// TODO Auto-generated method stub
			Log.d("Draw","In surfaceDestroyed");
			boolean retry = true;
            _thread.setRunning(false);
            while (retry) {
                try {
                    _thread.join();
                    retry = false;
                } catch (InterruptedException e) {
                    // we will try it again and again...
                }
            }
		}
	}
	
	class DrawingThread extends Thread {
        private SurfaceHolder _surfaceHolder;
        private DrawingPanel _panel;
        private boolean _run = false;
		
        public DrawingThread(SurfaceHolder surfaceHolder, DrawingPanel panel) {
        	Log.d("Draw","In DrawingThread Constructor");
            _surfaceHolder = surfaceHolder;
            _panel = panel;
        }
		
        public void setRunning(boolean run) {
            _run = run;
        }
		
        public SurfaceHolder getSurfaceHolder() {
            return _surfaceHolder;
        }
		
        @Override
        public void run() {
            Canvas c;
            while (_run) {
                c = null;
                try {
                    c = _surfaceHolder.lockCanvas(null);
                    synchronized (_surfaceHolder) {
                        _panel.onDraw(c);
                    }
                } finally {
                    // do this in a finally so that if an exception is thrown
                    // during the above, we don't leave the Surface in an
                    // inconsistent state
                    if (c != null) {
                        _surfaceHolder.unlockCanvasAndPost(c);
                    }
                }
            }
        }
    }
}
